<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          type="primary"
          @click="toQuery"
          size="mini">
          查询结果
        </el-button>
        <el-button
          @click="resetSearch"
          style="float: right;margin-right: 15px"
          size="mini">
          重置
        </el-button>
        <el-button
          v-permission="['admin','news:add']"
          @click="add"
          style="float: right;margin-right: 10px"
          class="btn-add"
          type="success"
          size="mini">
          添加
        </el-button>
      </div>
      <div style="margin-top: 20px">
        <el-form :inline="true" size="small" label-width="140px">
          <el-form-item label="id：">
            <el-input style="width: 180px" v-model="query.id" placeholder="请输入资讯id" clearable
                      @change="toQuery"></el-input>
          </el-form-item>
          <el-form-item label="标题：">
            <el-input style="width: 180px" v-model="query.title" placeholder="资讯标题模糊匹配" clearable
                      @change="toQuery"></el-input>
          </el-form-item>
          <el-form-item label="类型：">
            <el-select style="width: 100px" v-model="query.type" clearable @change="toQuery" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间：">
            <el-date-picker
              @change="toQuery"
              v-model="query.time"
              type="datetimerange"
              range-separator=":"
              class="el-range-editor--small filter-item"
              style="float: right;height: 30.5px;width: 350px"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-table v-loading="loading" border style="margin-top: 15px" :data="data" row-key="id" size="small">
      <el-table-column fixed="left" width="180" align="center" label="id" prop="id">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="点我复制" placement="top-start">
            <span style="cursor: pointer" v-copy:callback="handleCopied" v-copy="scope.row.id">{{scope.row.id}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column fixed="left" width="180" align="center" label="标题" prop="title"/>
      <el-table-column fixed="left" width="250" align="center" label="标签" prop="label">
        <template slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.label" style="margin-left: 10px;" :key="tag"
                  v-for="tag in scope.row.label.split(',')">{{tag}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="left" align="center" label="类型" prop="type">
        <template slot-scope="scope">
          <el-tag type="primary" size="mimi" v-if="scope.row.type===1">
            新闻
          </el-tag>
          <el-tag type="success" size="mimi" v-if="scope.row.type===2">
            职位
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="left" align="center" label="发布人" prop="issuer"/>
      <el-table-column align="center" prop="publishTime" label="发布时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建日期">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px"
                       align="center" fixed="right">
        <template slot-scope="scope">
          <el-button v-permission="['admin','news:update']" size="mini" type="primary"
                     :icon="'el-icon-edit'"
                     @click="edit(scope.row)">
          </el-button>
          <el-popover
            :ref="scope.row.id"
            placement="top"
            width="200">
            <p>确定删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
              <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定
              </el-button>
            </div>
            <el-button v-permission="['admin','news:del']" slot="reference"
                       type="danger" icon="el-icon-delete" size="mini">
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="page + 1"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"/>
    <el-dialog top="20" :visible.sync="dialog" :close-on-click-modal="false" :before-close="cancel"
               :title="isAdd ? '新增资讯' : '编辑资讯'" append-to-body width="70%">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="20%">
        <el-row>
          <el-col :span="12">
            <el-form-item label="封面：" prop="picture">
              <el-upload
                :show-file-list="false"
                :on-success="handleSuccess"
                :on-error="handleError"
                :headers="headers"
                :action="fileUploadApi"
                class="avatar-uploader">
                <img v-if="form.picture" :src="form.picture" title="点击上传封面" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资讯标题：" prop="title">
              <el-input v-model="form.title" style="width: 80%;" placeholder="请输入资讯标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布人：" prop="issuer">
              <el-input v-model="form.issuer" style="width: 80%;" placeholder="请输入发布人"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布时间：" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                placeholder="请输入发布时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签：" prop="labelList">
              <el-select
                style="width: 80%;"
                v-model="form.labelList"
                multiple
                :multiple-limit="3"
                @change="labelChange"
                @focus="searchLabels"
                filterable
                allow-create
                default-first-option
                placeholder="请选择文章标签">
                <el-option
                  v-for="item in labelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上架时间：" prop="upTime">
              <el-date-picker
                v-model="form.upTime"
                type="datetime"
                placeholder="请输入上架时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下架时间：" prop="downTime">
              <el-date-picker
                v-model="form.downTime"
                type="datetime"
                placeholder="请输入下架时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="外部导流资讯：" prop="isOutside">
              <el-radio-group v-model="form.isOutside">
                <el-radio :label="1">否</el-radio>
                <el-radio :label="2">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型：" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1">新闻</el-radio>
                <el-radio :label="2">职位</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资讯详情URL：" v-if="form.isOutside===2" prop="url">
              <el-input v-model="form.url" style="width: 80%;" placeholder="请输入资讯详情URL"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label-width="10%" label="上架星期：" prop="weekDays">
              <el-checkbox-group v-model="form.weekDays">
                <el-checkbox :label="1" name="1">星期一</el-checkbox>
                <el-checkbox :label="2" name="2">星期二</el-checkbox>
                <el-checkbox :label="3" name="3">星期三</el-checkbox>
                <el-checkbox :label="4" name="4">星期四</el-checkbox>
                <el-checkbox :label="5" name="5">星期五</el-checkbox>
                <el-checkbox :label="6" name="6">星期六</el-checkbox>
                <el-checkbox :label="7" name="7">星期日</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名字：" v-if="form.type===2" prop="companyName">
              <el-input v-model="form.companyName" style="width: 80%;" placeholder="请输入公司名字"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司性质：" v-if="form.type===2" prop="companyQuality">
              <el-input v-model="form.companyQuality" style="width: 80%;" placeholder="请输入公司性质"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司规模：" v-if="form.type===2" prop="companyScale">
              <el-input v-model="form.companyScale" style="width: 80%;" placeholder="请输入公司规模"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司行业：" v-if="form.type===2" prop="companyIndustry">
              <el-input v-model="form.companyIndustry" style="width: 80%;" placeholder="请输入公司行业"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="薪资上限：" v-if="form.type===2" prop="salaryUp">
              <el-input v-model="form.salaryUp" style="width: 80%;" placeholder="请输入薪资上限"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资下限：" v-if="form.type===2" prop="salaryDown">
              <el-input v-model="form.salaryDown" style="width: 80%;" placeholder="薪资下限"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司地址：" v-if="form.type===2" prop="areaArray">
              <el-cascader
                style="width: 80%;"
                v-model="form.areaArray"
                @change="areaChange"
                :options="areaList"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位申请URL：" v-if="form.type===2" prop="jobUrl">
              <el-input v-model="form.jobUrl" style="width: 80%;" placeholder="请输入职位申请URL"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label-width="10%" :label="form.type===1?'资讯详情：':'职位描述：'" v-show="form.isOutside===1"
                          prop="content">
              <div style="width: 90%; border: 1px solid #dcdfe6; border-radius: 4px; min-height: 150px;">
                <div id="toolbar" ref="toolbar" style="display: flex; flex-wrap: wrap;">
                </div>
                <div ref="editor_content" class="editor_content" style="border: 1px solid #ccc;min-height: 400px">
                  <!--<p>请输入内容</p>-->
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import initData from '@/mixins/initData'
  import {parseTime} from '@/utils/index'
  import {mapGetters} from 'vuex'
  import E from 'wangeditor'
  import {getToken} from '@/utils/auth'
  import {add, update, del} from '@/api/business/newsApi'
  import {add as addLabel, list as getLabelList} from '@/api/business/labelApi'
  import {areaList} from '@/utils/citys'

  export default {
    mixins: [initData],
    computed: {
      ...mapGetters([
        'fileUploadApi',
      ])
    },
    data() {
      return {
        areaList: areaList,
        typeOptions: [
          {
            value: 1,
            label: '新闻'
          }, {
            value: 2,
            label: '职位'
          }
        ],
        Editor: undefined,
        labelOptions: [],
        headers: {
          'Authorization': 'Bearer ' + getToken()
        },
        isAdd: true,
        delLoading: false,
        loading: false, dialog: false,
        form: {
          title: '',
          label: '',
          content: '',
          url: '',
          isOutside: 1,
          issuer: '',
          publishTime: '',
          picture: '',
          labelList: [],
          type: 1,
          upTime: '',
          downTime: '',
          weekDays: [1, 2, 3, 4, 5, 6, 7],
          companyName: '',
          companyQuality: '',
          companyScale: '',
          companyIndustry: '',
          salaryUp: '',
          salaryDown: '',
          jobUrl: '',
          province: '',
          city: '',
          area: '',
          provinceCode: '',
          cityCode: '',
          areaCode: '',
          areaArray: []
        },
        rules: {
          areaArray: [
            {required: true, message: '请选择职位地点', trigger: 'change', type: 'array'}
          ],
          companyName: [
            {required: true, message: '请选择公司名字', trigger: 'blur'}
          ],
          companyQuality: [
            {required: true, message: '请选择公司性质', trigger: 'blur'}
          ],
          companyScale: [
            {required: true, message: '请选择公司规模', trigger: 'blur'}
          ],
          companyIndustry: [
            {required: true, message: '请选择公司行业', trigger: 'blur'}
          ],
          salaryUp: [
            {required: true, message: '请选择薪资上限', trigger: 'blur'}
          ],
          salaryDown: [
            {required: true, message: '请选择薪资下限', trigger: 'blur'}
          ],
          picture: [
            {required: true, message: '请上传封面', trigger: 'blur'}
          ],
          url: [
            {required: true, message: '请输入url', trigger: 'blur'}
          ],
          title: [
            {required: true, message: '请输入资讯标题', trigger: 'blur'}
          ],
          isOutside: [
            {required: true, message: '请选择', trigger: 'blur'}
          ],
          publishTime: [
            {required: true, message: '请输入发布时间', trigger: 'blur'}
          ],
          issuer: [
            {required: true, message: '请输入发布者', trigger: 'blur'}
          ],
          upTime: [
            {required: true, message: '请输入上架时间', trigger: 'blur'}
          ],
          downTime: [
            {required: true, message: '请输入下架时间', trigger: 'blur'}
          ],
        }
      }
    },
    created() {
      this.init()
      this.searchLabels()
    },
    methods: {
      initEditor() {
        if (!this.Editor) {
          let editor = new E(this.$refs.toolbar, this.$refs.editor_content)
          editor.customConfig.zIndex = 1
          editor.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
          editor.customConfig.uploadImgHeaders = this.headers
          editor.customConfig.uploadImgMaxLength = 1
          editor.customConfig.uploadFileName = 'file'// 自定义文件名，不可修改，修改后会上传失败
          editor.customConfig.uploadImgServer = this.fileUploadApi // 上传图片到服务器
          editor.customConfig.uploadImgHeaders = {
            'ResType': 'array',
            'Authorization': 'Bearer ' + getToken()
          }
          editor.customConfig.onchange = (html) => {
            this.form.content = html
          }
          editor.create()
          this.Editor = editor
        }
        this.Editor.txt.html(this.form.content)
      },
      labelChange(list) {
        if (list && list.length > 0) {
          addLabel({
            name: list[list.length - 1],
            type: 1
          })
        }
      },
      searchLabels() {
        getLabelList({
          type: 1
        }).then(res => {
          this.labelOptions = []
          res.rows.forEach(i => {
            this.labelOptions.push({
              value: i.name,
              label: i.name
            })
          })
        })
      },
      handleSuccess(response, file, fileList) {
        this.$notify({
          title: '上传成功',
          type: 'success',
          duration: 2500
        })
        this.form.picture = response.data
      },
      handleError(e, file, fileList) {
        const msg = JSON.parse(e.message)
        this.$notify({
          title: msg.message,
          type: 'error',
          duration: 2500
        })
      },
      subDelete(id) {
        this.delLoading = true
        del(id).then(res => {
          this.delLoading = false
          this.$refs[id].doClose()
          this.init()
          this.$notify({
            title: '删除成功',
            type: 'success',
            duration: 2500
          })
        }).catch(err => {
          this.delLoading = false
          this.$refs[id].doClose()
        })
      },
      cancel() {
        this.resetForm()
      },
      resetForm() {
        this.dialog = false
        this.$refs['form'].resetFields()
        this.form = {
          title: '',
          label: '',
          content: '',
          url: '',
          isOutside: 1,
          issuer: '',
          publishTime: '',
          picture: '',
          labelList: [],
          type: '',
          upTime: '',
          downTime: '',
          weekDays: [1, 2, 3, 4, 5, 6, 7],
          companyName: '',
          companyQuality: '',
          companyScale: '',
          companyIndustry: '',
          salaryUp: '',
          salaryDown: '',
          jobUrl: '',
          province: '',
          city: '',
          area: '',
          provinceCode: '',
          cityCode: '',
          areaCode: '',
          areaArray: []
        }
      },
      areaChange(value) {
        if (value && value.length === 3) {
          this.form.provinceCode = value[0];
          this.form.cityCode = value[1];
          this.form.areaCode = value[2];
          this.calAreaName(value)
        }
      },
      calAreaName(value) {
        this.areaList.forEach(i => {
          //计算省
          if (i.value === value[0]) {
            this.form.province = i.label
            i.children.forEach(j => {
              if (j.value === value[1]) {
                this.form.city = j.label
                j.children.forEach(k => {
                  if (k.value === value[2]) {
                    this.form.area = k.label
                  }
                })
              }
            })
          }
        })
      },
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.isAdd) {
              this.doAdd()
            } else this.doEdit()
          } else {
            return false
          }
        })
      },
      doAdd() {
        this.form.label = this.form.labelList.join(',')
        add(this.form).then(res => {
          this.resetForm()
          this.$notify({
            title: '添加成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.init()
        }).catch(err => {
          this.loading = false
        })
      },
      doEdit() {
        this.form.label = this.form.labelList.join(',')
        update(this.form).then(res => {
          this.resetForm()
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.init()
        }).catch(err => {
          this.loading = false
        })
      },
      edit(data) {
        this.isAdd = false
        this.form = {
          id: data.id,
          title: data.title,
          label: data.label,
          content: data.content,
          url: data.url,
          isOutside: data.isOutside,
          issuer: data.issuer,
          publishTime: data.publishTime,
          picture: data.picture,
          labelList: data.label ? data.label.split(',') : [],
          type: data.type,
          upTime: data.upTime,
          downTime: data.downTime,
          weekDays: data.weekDays ? data.weekDays : [],
          companyName: data.companyName,
          companyQuality: data.companyQuality,
          companyScale: data.companyScale,
          companyIndustry: data.companyIndustry,
          salaryUp: data.salaryUp,
          salaryDown: data.salaryDown,
          jobUrl: data.jobUrl,
          province: data.province,
          city: data.city,
          area: data.area,
          provinceCode: data.provinceCode,
          cityCode: data.cityCode,
          areaCode: data.areaCode
        };
        if (data.provinceCode && data.cityCode && data.areaCode) {
          this.form.areaArray = [this.form.provinceCode, this.form.cityCode, this.form.areaCode]
        }
        this.dialog = true
        this.$nextTick(() => {
          this.initEditor()
        })
      },
      add() {
        this.dialog = true;
        this.isAdd = true;
        this.$nextTick(() => {
          this.initEditor()
        })
      },
      parseTime,
      beforeInit() {
        this.url = 'api/news/list'
        this.params = {page: this.page, size: this.size}
        const query = this.query
        if (query.title) {
          this.params['title'] = query.title
        }
        if (query.type) {
          this.params['type'] = query.type
        }
        if (query.id) {
          this.params['id'] = query.id
        }
        if (query.time && query.time.length > 0) {
          this.params['startTime'] = query.time[0]
          this.params['endTime'] = query.time[1]
        }
        return true
      },
      resetSearch() {
        this.query = {}
        this.init()
      },
    }
  }
</script>

<style scoped>
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
